package com.xxxx.util;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * java根据 url获取 json对象
 * @author openks
 * @since 2013-7-16
 *  需要添加java-json.jar才能运行
 */
public class wxdanmu {

    private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

    public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = new URL(url).openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = new JSONObject(jsonText);
            return json;
        } finally {
            is.close();
            // System.out.println("同时 从这里也能看出 即便return了，仍然会执行finally的！");
        }
    }

    public JsonObject getdanmu(String cid)throws IOException, JSONException {
        JsonObject object=new JsonObject();

        JSONObject json = readJsonFromUrl("https://api.acplay.net/api/v2/comment/"+cid+"?withRelated=true");

        JsonArray b=new JsonArray();
        JSONArray jsonArray=json.getJSONArray("comments");
        for(int i=0;i<jsonArray.length();i++){
            JsonObject a=new JsonObject();
            String TEXT=json.getJSONArray("comments").getJSONObject(i).get("m").toString();
            a.addProperty("text",TEXT);

            String[] X= json.getJSONArray("comments").getJSONObject(i).get("p").toString().split(",");
            double x= Double.parseDouble(X[0]);
            int x1= (int) x;
            int y= Integer.parseInt(X[1]);
            int z= Integer.parseInt(X[2]);

            int R=z/65536;
            int G=z/256%256;
            int B=z%256%256;
            String RGB="rgb("+R+","+G+","+B+")";
            a.addProperty("color",RGB);
            a.addProperty("time",x1);


            b.add(a);}
        object.addProperty("name", "8888");
        object.addProperty("danmu", 1);
        String[]  S={};
        object.add("danmuku", b);

        return object;
    }
}